#include "tformdoc.h"
#include "ui_tformdoc.h"
#include <QFile>
#include <QFileInfo>
#include <QFontDialog>

TFormDoc::TFormDoc(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::TFormDoc)
{
    ui->setupUi(this);

    setWindowTitle("New Doc[*]");
    setAttribute(Qt::WA_DeleteOnClose);

    connect(ui->plainTextEdit, &QPlainTextEdit::modificationChanged,
            this, &TFormDoc::setWindowModified);
}

TFormDoc::~TFormDoc()
{
    delete ui;
}

void TFormDoc::loadFromFile(const QString &fileName)
{
    QFile file(fileName);
    if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QTextStream stream(&file);
        ui->plainTextEdit->clear();
        ui->plainTextEdit->setPlainText(stream.readAll());
        file.close();

        QFileInfo fileInfo(fileName);
        QString str = fileInfo.fileName(); // 去除目录路径, 只拿到文件名
        m_fileName = str; // or fileName?
        m_fileOpened = true;
        setWindowTitle(str + "[*]");
    }
}

QString TFormDoc::currentFileName()
{
    return m_fileName;
}

bool TFormDoc::isFileOpened()
{
    return m_fileOpened;
}

void TFormDoc::saveToFile()
{
    setWindowModified(false);
}

void TFormDoc::setEditFont()
{
    QFont font;
    font = ui->plainTextEdit->font();
    bool ok(false);
    font = QFontDialog::getFont(&ok, font);
    if (ok) {
        ui->plainTextEdit->setFont(font);
    }
}

void TFormDoc::textCut()
{
    ui->plainTextEdit->cut();
}

void TFormDoc::textCopy()
{
    ui->plainTextEdit->copy();
}

void TFormDoc::textPaste()
{
    ui->plainTextEdit->paste();
}
